package com.yiwenup.leetcode.top_interview_150;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件描述
 *
 * @Project struct-algorithm
 * @Package com.yiwenup.leetcode.top_interview_150
 * @Author yiwenup
 * @Date 2024-12-20 22:31:06
 * @Description https://leetcode.cn/problems/contains-duplicate-ii/description/?envType=study-plan-v2&envId=top-interview-150
 */
public class No0219 {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        for (int i = 0; i < nums.length; i++) {
            int j = Math.min(i + k, nums.length);
            while (j > i) {
                if (nums[i] == nums[j]) {
                    return true;
                }
                j--;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        System.out.println(new No0219().containsNearbyDuplicate(new int[]{1, 2, 3, 1, 2, 3}, 2));
    }

    public boolean containsNearbyDuplicate2(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            Integer idx = map.get(nums[i]);
            if (idx != null && Math.abs(idx - i) <= k) {
                return true;
            }
            map.put(nums[i], i);
        }
        return false;
    }
}
